var version = ctx+"/common/plateform/base";

window.onerror = function(message, url, linenumber) {
    //接受三个参数,分别是错误信息,错误页面的url和错误行号
    //收集系统、浏览器信息，连同错误信息一起发给服务器
    //怎么发给服务器就随你啦,ajax/beacon都行
	console.log(message);
	console.log(url);
	// console.log(linenumber);
}

function deleteAllRow(tablename) {
    var tb = document.getElementById(tablename);

    if (tb) {
        var rowNum = tb.rows.length;
        for (i = 1; i < rowNum; i++) {
            tb.deleteRow(i);
            rowNum = rowNum - 1;
            i = i - 1;
        }
    }
}


function formReset(formName) {
    // document.getElementById("myForm").name.disabled=false;
    document.getElementById(formName).reset();
}


window.onpopstate = function(event) {
        if (event && event.state) {
            document.title = event.state.title;
            $('#main-tzba').html(event.state.html);
        }
    }
    //window.onpopstate = function(event){
    //	if((event || window.event) && event.state){
    //		document.title = event.state.title;
    //		$("#main").html(event.state.html);
    //	}
    //};


/**
 * 处理前台openRouter方法报错的情况
 */

var bootStrapJs = "";

function refreshBootStrap() {
    if (!bootStrapJs) {
        $.ajax({
            url: version + "/bootstrap/bootstrap.min.js?" + Math.random(),
            cache: false,
            async: false,
            success: function(js) {
                bootStrapJs = js;
            }
        });
    }
    window.eval(bootStrapJs);
    log("执行了");

}



var pageObj = {
        currentPage: 1,
        url: ""
    }
    /**
     * 通过url来区分不同的分页对象
     * @param url
     */

function list_url(url) {
    //如果是属于当前的分页
    if (pageObj["url"] && pageObj["url"] == url) {

        return pageObj.currentPage;

    } else {
        pageObj["currentPage"] = 1;
        pageObj["url"] = url;
        return pageObj["currentPage"];
    }
}



var pageObj = {
        currentPage: 1,
        url: ""
    }
/**
 * 通过url来区分不同的分页对象
 * @param url
 */

function getCurrentPage(url,rows) {
	pageObj.rows = rows;
    //如果是属于当前的分页
    if (pageObj["url"] && pageObj["url"] == url) {

//        return pageObj.currentPage;
       return  "&page="+pageObj.currentPage+"&rows="+pageObj.rows;

    } else {
    	if(sessionStorage.getItem("page")){
    		pageObj["currentPage"]=sessionStorage.getItem("page");
    		sessionStorage.clear();
    	}else{
    		 pageObj["currentPage"] = 1;
    	}
    	
        pageObj["url"] = url;
//        return pageObj["currentPage"];
        return  "&page="+pageObj.currentPage+"&rows="+pageObj.rows;
    }
}




/**
 * 生成分页
 *  var option= {
				   ele:$("#pageList")[0],
				   total:myDate.total,
				   fn:getTableList(),
				   url:url
			   }
 * @param ele
 * @param total
 * @param fn
 */
function generatePages(obj) {
    var option = {};
    if (obj.total == '0' || obj.total == 0) {
        option.currentPage = 1;
        pageObj["currentPage"] = 1;
       
    } else {
        option.currentPage = pageObj.currentPage;
    }
    
    //设置分页总数
    option.totalPages = getTotalPages(obj.total);
    //设置bootStrap版本
    option.bootstrapMajorVersion = 3;
    //设置对齐方式
    option.alignment = "center";

    //点击页码时的回调函数
    option.onPageClicked = function(event, originalEvent, type, page) {
        pageObj["currentPage"] = page;
        obj.fn();
    }

    //防止分页出错
    if ($(obj.ele).hasOwnProperty("bootstrapPaginator")) {
        $(obj.ele).bootstrapPaginator(option)
    } else {
        getBootStrapPaginator();

        $(obj.ele).bootstrapPaginator(option)
    }
}
pageObj["BootStrapPaginator"] = null;

function getBootStrapPaginator() {

    if (pageObj["BootStrapPaginator"]) {
        window.eval(pageObj["BootStrapPaginator"]);
    } else {
        $.ajax({
            type: "get",
            url: version + "/utils/bootstrap-paginator.js#",
            async: false,
            success: function(msg) {
                pageObj["BootStrapPaginator"] = msg;
                window.eval(msg);
            }
        });

    }

}


/***
 * 获取总的分页数
 */
function getTotalPages(total) {
	if(total==0){
		return 1;
	}
    var totalString = "" + total / pageObj.rows;

    totalString = totalString.split(".");
    if (totalString.length > 1) {
        total = Number(totalString[0]) + 1;
    } else {
        total = Number(totalString[0]);
    }

    return total;

}

function log(value) {
    console.log(value);
}


/**       
 * 对Date的扩展，将 Date 转化为指定格式的String
 * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符
 * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
 * eg:
 * (new Date()).pattern("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
 * (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04
 * (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04
 * (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04
 * (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
 */
Date.prototype.pattern = function(fmt)
{
var o = {
  "M+": this.getMonth() + 1, //月份           
  "d+": this.getDate(), //日           
  "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时           
  "H+": this.getHours(), //小时           
  "m+": this.getMinutes(), //分           
  "s+": this.getSeconds(), //秒           
  "q+": Math.floor((this.getMonth() + 3) / 3), //季度           
  "S": this.getMilliseconds() //毫秒           
};
var week = {
  "0": "/u65e5",
  "1": "/u4e00",
  "2": "/u4e8c",
  "3": "/u4e09",
  "4": "/u56db",
  "5": "/u4e94",
  "6": "/u516d"
};
if (/(y+)/.test(fmt))
{
  fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
if (/(E+)/.test(fmt))
{
  fmt = fmt.replace(RegExp.$1, (
    (RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[this.getDay() + ""]);
}
for (var k in o)
{
  if (new RegExp("(" + k + ")").test(fmt))
  {
    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(
      ("" + o[k]).length)));
  }
}
return fmt;
}

var currentTable = "";
var tableHeadArray = [];
var tdCount = 1;
var currentTableEle = "null";
/**
 * tableEle:tableId
 * cellNum:插入的单元格数字
 * insertHtml:插入的内容
 */
function insertCustomCell(cellNum,insertHtml){
	var cell = currentTable.insertCell(cellNum);
	var tempTable = $(currentTable).parents("table")[0]
	if(currentTableEle=='null' || currentTableEle.id != tempTable.id){
		currentTableEle = tempTable;
		tdCount = 1;
		tableHeadArray = [];
		
	}
	
	//需要获取到当前单元格的表头
	var tableHead = $($(currentTable).parents("table")[0]).find(".active").find("th");
	if(tableHead && tableHead[0]){}
	else{
		tableHead =$($(currentTable).parents("table")[0]).find(".active").find("td");
	}
	
	if(!tableHead[0]){
		tableHead =$($(currentTable).parents("table")[0]).find("td");
	}
	if(!tableHead[0]){
		tableHead =$($(currentTable).parents("table")[0]).find("th");
	}
	
	var curentTableHeadLength = tableHead.length;
	
	var tableCell = tableHead[cellNum];
	
	var currnetEleHeight = 0;
	if(tableCell.width){
		currnetEleHeight = tableCell.width;
		cell.width = tableCell.width;
	}
	else{
		
		currnetEleHeight = cell.offsetWidth;
	}
	currnetEleHeight = cell.offsetWidth-20;
	
	
	
	//如果当亲的单元格序号小余table的head数量, 并且统计数==1
	if(!tableHeadArray[cellNum] && tdCount==1){
		tableHeadArray[cellNum] = currnetEleHeight;
	}else{
		currnetEleHeight = tableHeadArray[cellNum];
		tdCount++;
	}
	
		
	cell.style.overflow = "hidden";
	if(!insertHtml || !$.trim(insertHtml)){
		insertHtml = "";
	}
	cell.innerHTML = '<div title='+insertHtml+' style="white-space:nowrap;width:'+currnetEleHeight+'px">'+insertHtml+'</div>';
}

function insertHtmlToCell(cellNum,insertHtml,title){
	var cell = currentTable.insertCell(cellNum);
	var tempTable = $(currentTable).parents("table")[0]
	if(currentTableEle=='null' || currentTableEle.id != tempTable.id){
		currentTableEle = tempTable;
		tdCount = 1;
		tableHeadArray = [];
		
	}
	
	//需要获取到当前单元格的表头
	var tableHead = $($(currentTable).parents("table")[0]).find(".active").find("th");
	if(tableHead && tableHead[0]){}
	else{
		tableHead =$($(currentTable).parents("table")[0]).find(".active").find("td");
	}
	
	if(!tableHead[0]){
		tableHead =$($(currentTable).parents("table")[0]).find("td");
	}
	if(!tableHead[0]){
		tableHead =$($(currentTable).parents("table")[0]).find("th");
	}
	
	var curentTableHeadLength = tableHead.length;
	
	var tableCell = tableHead[cellNum];
	
	var currnetEleHeight = 0;
	if(tableCell.width){
		currnetEleHeight = tableCell.width;
		cell.width = tableCell.width;
	}
	else{
		
		currnetEleHeight = cell.offsetWidth;
	}
	currnetEleHeight = cell.offsetWidth-20;
	
	
	
	//如果当亲的单元格序号小余table的head数量, 并且统计数==1
	if(!tableHeadArray[cellNum] && tdCount==1){
		tableHeadArray[cellNum] = currnetEleHeight;
	}else{
		currnetEleHeight = tableHeadArray[cellNum];
		tdCount++;
	}
	
		
	cell.style.overflow = "hidden";
	if(!insertHtml || !$.trim(insertHtml)){
		insertHtml = "";
	}
	//cell.innerHTML = '<div title='+insertHtml+' style="white-space:nowrap;width:'+currnetEleHeight+'px">'+insertHtml+'</div>';

	
	cell.innerHTML = '<div title='+title+' style="white-space:nowrap;width:'+currnetEleHeight+'px">'+insertHtml+'</div>';
}

/**
 * 搜索传入的Array数组,查找对应的key值是否含有value 
 * @returns:new Array();
 */
function searchArray(searchArray,searchKey,searchValue){
	var newArray = [];
	var count = 0;
	if(searchArray){
		for(var i=0;i<searchArray.length;i++){
			var currentObj = searchArray[i];
			if(currentObj && currentObj.hasOwnProperty(searchKey) && currentObj[searchKey] == searchValue){
				newArray[count] = currentObj;
				count++;
			}
		}
	}
		return newArray;
}


/***
 * 转化中文路径为英文路径
 */
function convertChineseUrlToEng( path){
	var url = {};
	url.path =  path
	
	   $.ajax({
		   type:"post",
		   url:ctx+"/admin/prodocment/pathConverter",
	   	   data:url,
	   	   async:false,
	   	   success:function(msg){
	   		url.path = msg;
	   	   }
	   });
	return url.path;
}

